import { KeyboardEvent } from './event'
import { TextModel, SelectionModel } from './models'
import { InsertTextOperation, SetSelectionOperation, RemoveTextOperation } from './operations'
import { RenderView } from './view'

class Editor {
    textModel_;
    selectionModel_;
    view_;
    eventHandler;
    container;
    constructor(container) {
        this.container = container
    }

    init() {
        this.eventHandler = new KeyboardEvent(this, this.container, this.view_)
        this.textModel_ = new TextModel()
        this.selectionModel_ = new SelectionModel(this.textModel_)
        this.view_ = new RenderView(this.textModel_, this.selectionModel_, this.container)
        this.eventHandler.addListeners()
    }

    getTextModel() {
        return this.textModel_ // 跳转到数据模型
    }

    getSelectionModel() {
        return this.selectionModel_ // 跳转到选区模型
    }

    setSelection(anchor: number, focus: number) {
        const setSelectionOperaction = new SetSelectionOperation({ anchor, focus })
        setSelectionOperaction.apply(this)
    }

    insertTextAtCursor(text) {
        const selection = this.selectionModel_.getSelection()
        let startIndex = selection.anchor
        let cursorIndex;
        if (!this.selectionModel_.isCollapsed()) {
            const removeTextOperation = new RemoveTextOperation(selection.anchor, selection.focus)
            removeTextOperation.apply(this)
            if (this.selectionModel_.isBackward()) {
                startIndex = selection.focus;
            }
        }
        cursorIndex = startIndex + text.length
        const insertTextOperation = new InsertTextOperation(text, startIndex);
        insertTextOperation.apply(this)
        this.setSelection(cursorIndex, cursorIndex)
    }

    deleteTextAtCursor() {
        const selection = this.selectionModel_.getSelection()
        let startIndex = selection.anchor
        if (!this.selectionModel_.isCollapsed()) {
            const removeTextOperation = new RemoveTextOperation(selection.anchor, selection.focus)
            removeTextOperation.apply(this)
            if (this.selectionModel_.isBackward()) {
                startIndex = selection.focus;
            }
        } else if (selection.anchor > 0) {
            const removeTextOperation = new RemoveTextOperation(selection.anchor - 1, selection.focus)
            removeTextOperation.apply(this)
            startIndex--
        }
        this.setSelection(startIndex, startIndex)
    }

    // 撤销
    undo() {

    }

    // 回退
    redo() {

    }
}

export default Editor;
